<?php


namespace Beerus\Modules\Peanut\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\pockets\excel\DownExcel;
use Doraemon\cache\UserNick;
use Doraemon\model\Peanut\DesignerRIDModel;
use Doraemon\model\Peanut\RakeBackModel;
use Doraemon\model\Peanut\RakeBackRecordModel;
use Doraemon\service\Peanut\RakeBackService;
use Doraemon\service\User;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;
use Biz\tools\helper\Common;
use PhpOffice\PhpSpreadsheet\IOFactory;
use TencentCloud\Ssm\V20190923\Models\UpdateSecretRequest;

/**
 * 返佣链接管理
 */
class IndexController extends Controller
{
    const TAB_LIST = 'list'; //返佣列表
    const TAB_HISTORY= 'history'; //上传历史
    const EXCEL_HEADER = '设计师RID,商品ID';
    /**
     * 返佣链接管理
     *
     * @param Content $content
     * @param Request $request
     * @return void
     */
    public function index(Content $content, Request $request)
    {
        $where = $this->_buildListWhere($request->all());
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $limit = [($page - 1) * $pageSize, $pageSize];

        $preUrl = str_replace('beerus.', 'yapi.', str_replace('admin/Peanut/index', '', $request->url()));

        if(false !== strpos($preUrl, 'yapi.haohaozhu.me')) {
            $preUrl = 'https://yapi.haohaozhu.cn/';
        }

        $sort = $request->input('_sort', []);
        $list = RakeBackModel::getList($where, $limit, $sort);

        $designerRIDMap = [];
        if(!empty($list['list'])) { //数据都不为空
            $relationIdList = array_column($list['list'], 'relation_id');//取出所有设计师RID
            $relationIdList = array_unique($relationIdList); //去重重复数据
            $designerRIDList =  DesignerRIDModel::selectData(['relation_id' => $relationIdList], ['relation_id', 'uid']);
            if (!empty($designerRIDList))  {
                foreach ($designerRIDList as $dv) {
                    $designerRIDMap[$dv['relation_id']] = $dv['uid'];
                }
            }
        }

        return $content
                    ->header('返佣链接列表')
                    ->breadcrumb(['text' => '返佣链接'])
                    ->row($this->_getTab(self::TAB_LIST, $this->_formatListGrid($list, $designerRIDMap, $page, $pageSize, $preUrl)->render()))
                    ;
    }


    /**
     * 返佣链接excel上传历史记录
     *
     * @param Content $content
     * @param Request $request
     * @return void
     */
    public function history(Content $content, Request $request)
    {
        $where = $this->_buildListWhere($request->all());
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $limit = [($page - 1) * $pageSize, $pageSize];


        $list = RakeBackRecordModel::getList($where, $limit);


        return $content
                    ->header('返佣链接列表')
                    ->breadcrumb(['text' => '返佣链接'])
                    ->row($this->_getTab(self::TAB_HISTORY, $this->_formatHistoryGrid($list, $page, $pageSize)))
                    ;
    }

    /**
     * 生成返佣链接grid
     *
     * @param [type] $list  返佣列表
     * @param [type] $designerRIDMap 设计师RID对应关系map
     * @param [type] $page 页码
     * @param [type] $pageSize 每页数量
     * @param [type] $preUrl 域名前缀
     * @return void
     */
    public function _formatListGrid($list, $designerRIDMap, $page, $pageSize, $preUrl)
    {
        $options = array(
            "currentPage" => $page,
            "perPage" => $pageSize,
        );


        $gridModel = new pGridDataModel($list['list'], $list['total'], $options);

        $grid = Admin::grid($gridModel,
            function (Grid $grid)use($pageSize, $designerRIDMap, $preUrl) {
                $grid->paginate($pageSize);
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1/3, function ($filter) {
                        $filter->group('Find', function ($group) {
                            $group->equal('设计师uid');
                            $group->equal('设计师昵称');
                            $group->equal('阿里妈妈RID');
                        });
                    });
                    $filter->column(1 / 3, function (Grid\Filter $filter) {
                        $filter->equal('product_id', '商品ID')->placeholder('输入商品ID');
                    });
                    $filter->column(1 / 3, function (Grid\Filter $filter) {
                       $filter->equal('data_status', '状态')->select(RakeBackModel::ALL_STATUS);
                    });
                    $filter->expand();
                });

                $grid->disableExport();
                $grid->disableRowSelector();
                // $grid->disableCreateButton();
                $grid->disableActions();

                $grid->column('id', 'id')->style("min-width:50px");
                $grid->column('uid', '设计师UID')->display(function () use ($designerRIDMap) {
                    if(isset($designerRIDMap[$this->relation_id])) {
                        return $designerRIDMap[$this->relation_id];
                    }
                    return '';
                })->style("min-width:100px");
                $grid->column('nickname', '设计师昵称')->display(function () use ($designerRIDMap) {
                    if(isset($designerRIDMap[$this->relation_id])) {
                        return UserNick::uid2nick($designerRIDMap[$this->relation_id]);
                    }
                    return '';
                })->style("min-width:100px");;
                $grid->column('relation_id', '设计师RID')->style("min-width:50px");
                $grid->column('product_id', '商品ID');

                $grid->column('edittime', '转链时间')->display(function () {
                    return date("Y-m-d H:i:s", $this->edittime>0?$this->edittime:$this->addtime);
                })->style("min-width:150px");

                $grid->column('data_status', '状态')->display(function () {
                    return RakeBackModel::ALL_STATUS[$this->data_status];
                })->style("min-width:50px");

                $grid->column('total', '点击次数')->style("min-width:100px;text-align:center");


                $grid->column('short_url', '短链接/失败原因')->display(function () use($preUrl) {
                    return empty($this->url)?$this->reason:RakeBackModel::getUrl($this->id_md5, $preUrl);
                });

                $grid->column('tbk_tpwd', '淘口令')->style("min-width:150px;word-break:break-all");


                $grid->column('url', '返佣长链接')->style("min-width:400px;word-break:break-all");
                $grid->column('product_url', '原始商品链接')->style("min-width:400px;word-break:break-all");




            }
        );
        $url = $_SERVER["REQUEST_URI"];
        $data_url = explode('?',$url);
        $export_url = $data_url[1] ? :'';
        //增加自定义导出工具按钮
        $grid->tools(function ($tools) use ($export_url) {
            $url = url('/admin/Peanut/exportData?'.$export_url);
            $button = '<div class="btn-group download" style="margin-right: 10px">
    <a class="btn btn-sm btn-twitter" title="导出" target="_blank" href="'.$url.'"><i class="fa fa-download"></i><span class="hidden-xs"> 导出</span></a>
</div>';
            $tools->append($button);
        });
        return $grid;
    }

    /**
     * 导出数据
     * 前期只导出前2000条
     *
     * @param Request $request
     * @return void
     */
    public function exportData(Request $request)
    {
        $where = $this->_buildListWhere($request->all());
        $limit = [0, 2000];

       $preUrl = str_replace('beerus.', 'yapi.', str_replace('admin/Peanut/exportData', '', $request->url()));

        if(false !== strpos($preUrl, 'yapi.haohaozhu.me')) {
            $preUrl = 'https://yapi.haohaozhu.cn/';
        }

        $sort = [];
        $list = RakeBackModel::getList($where, $limit, $sort);
       
        $result = [];

        foreach ($list['list'] as $val) {
             $url = '';
             if(!empty($val['url'])) {
                 $url = RakeBackModel::getUrl($val['id_md5'], $preUrl);
             }
            $result[] = [
                'relation_id' => $val['relation_id'],
                'product_id' => $val['product_id'],
                // 'total' => $val['total'],
                // 'data_status' => RakeBackModel::ALL_STATUS[$val['data_status']],
                'tbk_url' => RakeBackModel::STATUS_NORMAL == $val['data_status'] ? $val['url']:$val['reason'],
                'url' => $url,
                'tbk_tpwd' => $val['tbk_tpwd'],
                'reason' => $val['reason']
            ];
        }

         
     

        $title = '返佣链接-'.date('YmdHi');
        $header = ['设计师RID', '商品ID', '淘宝地址', '短链接',  '淘口令', '失败原因'];
        $letter = range('A', 'F');
        $excelObj = new DownExcel();
        $excelObj->setFileName($title);
        $excelObj->setSheetTitle($title);

        //设置列宽
        $widths = ['A' => 15, 'B' => 15, 'C' => 100, 'D' => 50, 'E' => 50, 'F' => 50];
        $excelObj->setWidth($widths);
        //默认单元格居中
        // $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        foreach ($header as $key => $value) {
            //设置字体
            $excelObj->setFrontName($letter[$key]);
            //设置加粗
            $excelObj->setFrontBold("$letter[$key]1");
            //设置大小
            $excelObj->setFrontSize($letter[$key]);
        }
        $excelObj->create($result, $header, null, '', [], [], [], ['A', 'B']);
    }

    /**
     * 构建请求where
     *
     * @param [type] $params  请求参数
     * @return array
     */
    private function _buildListWhere($params)
    {
        $where = [];

        if (isset($params["data_status"]) && $params["data_status"]) { //状态
            $where['data_status'] = $params["data_status"];
        }


        if(!empty($params['product_id'])) { //商品ID
            $where['product_id'] = $params['product_id'];
        }

        if(!empty($params['admin_id'])) { //创建者
            $where['admin_id'] = $params['admin_id'];
        }

        if(!empty($params['start_time'])) {  //开始时间
            $where['addtime[>=]'] = strtotime($params['start_time']);
        }

        if(!empty($params['end_time'])) { //结束时间
            $where['addtime[<=]'] = strtotime($params['end_time']) + 86400;
        }


        if (isset($params['Find'])) {
            $find = $params['Find'];
            $findGroup = $params['Find_group'];
            if (2 == $findGroup) {
                $where['relation_id'] = $find;
            } else if (1 == $findGroup || 0 == $findGroup) {
                if (1 == $findGroup) {
                    $find = User::getUidByNick($find);//昵称转换uid
                }
                if (!empty($find)) { //uid转换relation_id
                    $find = DesignerRIDModel::getOne(['uid' => $find], 'relation_id');
                }
                if (!empty($find)) {
                    $where['relation_id'] = $find;
                }

            }
        }

        return $where;
    }

    /**
     * 更加路由返回不同的tab
     *
     * @param [type] $tabType 路由类型
     * @param [type] $gridRender  gridRender
     * @return void
     */
    private function _getTab($tabType, $gridRender)
    {

        $tab = new Tab();
        if (self::TAB_LIST == $tabType) {
            $tab->add('返佣列表', $gridRender, true);
            $tab->addLink('提交生成任务', '/admin/Peanut/history');
        } else {
            $tab->addLink('返佣链接', '/admin/Peanut/index');
            $tab->add('提交生成任务', $gridRender, true);
        }
        return $tab;
    }

    /**
     * 下载导入模板
     *
     * @return void
     */
    public function downloadTemplate()
    {
        // $csv_data = self::EXCEL_HEADER;
        // $file_name = '设计师返佣链接生成.csv';
        // header("Content-type:text/csv;");
        // header("Content-Disposition:attachment;filename=" . $file_name);
        // header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        // header('Expires:0');
        // header('Pragma:public');
        // echo $csv_data;

        $title = '设计师返佣链接生成';
        $header = ['设计师RID', '商品ID'];
      //  $letter = range('A', 'B');
        $excelObj = new DownExcel();
        $excelObj->setFileName($title);
        $excelObj->setSheetTitle($title);

        //设置列宽
        $widths = ['A' => 15, 'B' => 15];
        $excelObj->setWidth($widths);
        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        $excelObj->create([['', '']], $header, null, '', [], [], [], ['A', 'B']);
    }

    /**
     * 生成上传历史记录grid和上传表单
     *
     * @param [type] $list  数据
     * @param [type] $page 页码
     * @param [type] $pageSize 每页数量
     * @return void
     */
    private function _formatHistoryGrid($list, $page, $pageSize)
    {
        $form = new Form();
        // $form->text('pic_url_file',"展示上传的文件")->placeholder("用于展示上传的文件")->disable();
        // $form->fileUpload("pic_url_file", '用于快速转换返佣商品链接', ['drop_zone_enabled' => false, 'allowed_file_extensions' => ["xlsx","xls"], 'showPreview' => false])->help('请下载模板进行填写，填写完成之后上传');
        // $form->hidden('pic_url_file');
        $form->file('excel', '上传Excel', ['drop_zone_enabled' => false, 'allowed_file_extensions' => ["xlsx","xls"], 'showPreview' => false])->help('请认真核对excel格式，第一列为设计师RID， 第二列为商品ID'); //->rules('mimes:xls,xlsx')->required()

        $form->action("/admin/Peanut/uploadFile");
        $form->html('<div class="btn-group pull-left">
                <a  class="btn btn-info pull-right" href="/admin/Peanut/downloadTemplate" target="_blank">模板下载</a>
            </div>');
        $form->disableReset();

        $uploadHistory = $this->_formatHistoryRecordGrid($list, $page, $pageSize);
        return $form->render().$uploadHistory->render();
    }

    /**
     * 生成上传历史记录grid
     *
     * @param [type] $list 数据
     * @param [type] $page 页码
     * @param [type] $pageSize 每页数量
     * @return void
     */
    private function _formatHistoryRecordGrid($list, $page, $pageSize)
    {
        $gridModel = new pGridDataModel($list['list'], $list['total'], array(
            "currentPage" => $page,
            "perPage" => $pageSize,
        ));

        $grid = Admin::grid($gridModel,
            function (Grid $grid) use($pageSize) {
                $grid->paginate($pageSize);
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('admin_id', '创建者')->select(Admin::user()->pluck('name', 'id')->toarray());
                        $filter->equal('data_status', '链接状态')->select(RakeBackRecordModel::ALL_STATUS)->default('');
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('start_time', '开始时间')->date();
                        $filter->equal('end_time', '结束时间')->date();
                    });
                });

                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();
                $grid->disableActions();
                $grid->column('id', "任务id");

                $grid->column('operate', '操作人')->display(function (){
                    return Admin::user()->find($this->admin_id)->name;
                });

                $grid->column('addtime', '操作时间')->display(function (){
                    return date("Y-m-d H:i:s", $this->addtime);
                });

                $grid->column('data_status', '任务状态')->display(function (){
                    return  RakeBackRecordModel::ALL_STATUS[$this->data_status];
                });
            }
        );
        return $grid;
    }

    /**
     * 上传文件，分析落库
     *
     * @param Request $request
     * @return void
     */
    public function uploadFile(Request $request)
    {
        ini_set('memory_limit', '100M');

        $adminEmail = Admin::user()->email;
        if (!$adminEmail) {
            $error = new MessageBag([
                'title' => '请设置管理员Email'
            ]);

            return back()->with(compact('error'));
        }
        $allData = $request->all();

        $rules = [
            'excel' => 'mimes:xlsx,xls'

        ];

        //验证参数
        $returnMsg = Common::validatorRule($rules, $allData);
        if ($returnMsg !== true) {
            $error = new MessageBag([
                'title' => '请上传xlsx或者xls格式文件'
            ]);
            return back()->with(compact('error'));
        }
        $file = $allData["excel"];

        //获取后缀
        $file_array = explode(".", $file->originalName);
        $file_extension = strtolower(array_pop($file_array));
        if('xls' != $file_extension) {
            $file_extension = 'xlsx';
        }
        $dir = sys_get_temp_dir() . DIRECTORY_SEPARATOR; //获取系统临时目录
        $fileName = $dir.md5($file.rand(1, 10000000)) . date('YmdHis') . $file_extension;
        $res = move_uploaded_file($file, $fileName);
        if (!$res) {
            $error = new MessageBag([
                'title' => '保存文件失败'
            ]);

            return back()->with(compact('error'));
        }

        $objReader = IOFactory::createReaderForFile($fileName); //分分析数据使用
        $objReader->setReadDataOnly(true); //只读取数据,会智能忽略所有空白行和特殊的,这点很重要！！！
        $objReader->setIncludeCharts(false);//加载文件时删除图表
        $objReader->setLoadAllSheets(); //加载所有表格
        $objReader->setReadEmptyCells(false);  //不加载空的
        $objPHPExcel = $objReader->load($fileName);

        $data = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);

        //判断数据是否存在
        if (empty($data) || !is_array($data)) {
            $error = new MessageBag([
                'title' => '无法获取到文件数据'
            ]);

            return back()->with(compact('error'));
        }

        // if(2 != count($data[1])) {
        //     $error = new MessageBag([
        //         'title' => '文件表头错误， 列数为'.count($data[1])
        //     ]);

        //     return back()->with(compact('error'));
        // } else {
        if (self::EXCEL_HEADER  != trim($data[1]['A']).','.trim($data[1]['B'])) {
            $error = new MessageBag([
                'title' => '文件表头错误, 表头内容为'.$data[1]['A'].','.$data[1]['B']
            ]);

            return back()->with(compact('error'));
        }
        // }
        //是否存在数据
        if (2 > count($data)) {
            $error = new MessageBag([
                'title' => '无法获取到文件数据'
            ]);

            return back()->with(compact('error'));
        }
        

        // 先在上传历史表里插一条记录
        $adminId = Admin::user()->id;
        $insertData = [
            'admin_id' => $adminId,
            'data' => json_encode($data),
            'addtime' => time(),
            'admin_email' => Admin::user()->email, //冗余操作人邮箱
            'data_status' => RakeBackRecordModel::STATUS_EXPORT
        ];

        $historyId = RakeBackRecordModel::addInfo($insertData);
        if (empty($historyId)) {
            $error = new MessageBag([
                'title' => '添加生成任务失败，请重试'
            ]);
            return back()->with(compact('error'));
        }

        $success = new MessageBag([
            'title' => '提交成功'
        ]);

        return redirect(url('/admin/Peanut/history'))->with(compact('success'));
    }


    /**
     * 新增
     * @param Request $request
     * @param Content $content
     * @param Form $form
     * @return Content
     */
    public function create(Request $request, Content $content, Form $form)
    {
        $form->divider();
        $form->text('relation_id', '设计师RID')->required();
        $form->text('product_id', '商品ID')->required();
        $form->confirm('确定转换吗？');
        $form->action('/admin/Peanut/save');

        return $content
            ->header('新增')
            ->description(' ')
            ->breadcrumb(
                ['text' => '返佣列表', 'url' => '/Peanut/index'],
                ['text' => '转换链接']
            )
            ->row($form);
    }

    /**
     * 新增保存
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
    */
    public function save(Request $request)
    {
        $params = $request->all();
        //校验参数
        $res_msg = Common::validatorRule([
            "relation_id" => 'required',
            "product_id" => 'required|integer'
        ], $params);
        if ($res_msg !== true) {
            $error = new MessageBag([
                'title' => $res_msg,
            ]);
            return back()->with(compact('error'));
        }
        
        $idMd5 = RakeBackModel::createIdMd5($params['relation_id'], $params['product_id']);;
        $oldRakeBack =  RakeBackModel::getOne($idMd5, ['data_status', 'id', 'id_md5']);

        $itemUrl = ''; //返佣链接

        //已经生成过
        if(!empty($oldRakeBack)) {
            //生成成功
            if(!empty($oldRakeBack['url'])) {
                $itemUrl = $oldRakeBack['url'];
            }
        }

        //返佣链接, 淘口令, 失败原因
        list($itemUrl, $tbkTpwd, $reason) = RakeBackService::getItemUrlAndTbkTpwd($itemUrl, $params['product_id'], $params['relation_id']);



        if (!empty($itemUrl)) {
            $oid = '';
            if(!empty($oldRakeBack)) {
                $oid = $oldRakeBack['id'];
            }
            $successStr = RakeBackService::saveData($oid, $itemUrl, $tbkTpwd, $params['relation_id'], $params['product_id'], $idMd5);
            $success = new MessageBag([
                'title' => $successStr,
            ]);
            return redirect('/admin/Peanut/index')->with(compact('success'));
        } else {
            if(empty($oldRakeBack)) {
                $insertData = [
                    'relation_id' => $params['relation_id'],
                    'product_id' => $params['product_id'],
                    'id_md5' => $idMd5,
                    'url' => '',
                    'tbk_tpwd' => $tbkTpwd,
                    'reason' => $reason,
                    'data_status' => RakeBackModel::STATUS_ERROR,
                    'addtime' => time(),
                    'edittime' => time()
                ];
                RakeBackModel::insertAll($insertData);
                $reason = '转换失败:'.$reason;
            } else {
                $reason = '再次转换失败:'.$reason;
            }
            $error = new MessageBag([
                'title' => $reason,
            ]);

            return redirect('/admin/Peanut/index')->with(compact('error'));
        }
    }
}